package com.sj.security;

import com.sj.entity.User;
import com.sj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoqi
 * Date: 2022-03-10
 * Time: 上午 9:26
 * Description: springSecurity登录service
 *
 * @author xiaoqi
 * @since 2022-03-10
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.lambdaQuery().eq(User::getUsername, username).one();
        if (user == null) {
            throw new UsernameNotFoundException("用户名未找到");
        }
        return new SecurityUser(user.getId(), user.getUsername(), user.getPassword(), this.getAuthorities(user.getId(), user.getUsername()));
    }

    public Collection<? extends GrantedAuthority> getAuthorities(Integer id, String username) {
        String authorities = userService.getAuthorities(id, username);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authorities);
    }
}